package com.example.backblog.config;

import cn.hutool.core.io.IoUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTUtil;
import com.example.backblog.vo.ApiResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.example.backblog.util.ConstantUtil.USER_SESSION;
import static com.example.backblog.util.ErrorCodeUtil.NO_LOGIN_ERROR_CODE;


/**
 * 登录控制器
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        // 使用 shiro 验证
        if (!subject.isAuthenticated()) {
//            IoUtil.writeObj(response.getOutputStream(),false, ApiResult.error(NO_LOGIN_ERROR_CODE,"用户未登录",null));
            response.getWriter().write(
                    new ObjectMapper().writeValueAsString(ApiResult.error(NO_LOGIN_ERROR_CODE,"no login",null))
            );
            response.flushBuffer();
            return false;
        }
        return true;
    }
}
